package com.example.repeatsubmit.interceptor;

import com.example.repeatsubmit.annotation.CloseRepeatSubmit;
import com.example.repeatsubmit.exception.RepeatSubmitException;
import com.example.repeatsubmit.policy.RepeatPolicy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.invoke.MethodHandle;

/**
 * @author caoqianhuan
 * @date 2022/8/19
 * @Description:
 */
@Component
public class RepeatInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("放重复拦截器执行");
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            CloseRepeatSubmit annotation = handlerMethod.getMethod().getAnnotation(CloseRepeatSubmit.class);
            if (annotation == null) {
                return HandlerInterceptor.super.preHandle(request, response, handler);
            }
            RepeatPolicy repeatPolicy = annotation.policy().getRepeatPolicy();
            repeatPolicy.setInterval(annotation.interval());
            if (repeatPolicy.isRepeatSubmit(request)) {
                throw new RepeatSubmitException("不能重复提交");
            }
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }
}
